#ifndef WORKERTHREAD_H
#define WORKERTHREAD_H

#include <QThread>
#include <QDebug>
#include <QMutex>


class WorkerThread : public QThread
{
    Q_OBJECT

public:
    //是否需要被停止标志位初始值设置为false
    explicit WorkerThread(QObject *parent = 0)
        : QThread(parent),m_bNeedStopped(false)
    {
        qDebug() << "Worker Thread : " << QThread::currentThreadId();
        m_progressValue = 0;
    }

    ~WorkerThread()
    {
        stop();
        quit();
        wait();
    }

    void stop()
    {
        qDebug() << "Worker Stop Thread : " << QThread::currentThreadId();
        QMutexLocker locker(&m_mutex);
        m_bNeedStopped = true;
    }

protected:
    virtual void run() Q_DECL_OVERRIDE {
        //线程开始运行，是否需要被停止设置为false
        m_bNeedStopped = false;
        qDebug() << "Worker Run Thread : " << QThread::currentThreadId();
        while (m_progressValue < 100)
        {
            // 休眠50毫秒
            msleep(50);
            ++m_progressValue;
            qDebug() << " emit result for the value " << m_progressValue;

            // 准备更新
            emit resultReady(m_progressValue);

            // 检测是否需要停止
            {
                QMutexLocker locker(&m_mutex);
                if (m_bNeedStopped)
                    break;
            }
            // locker超出范围并释放互斥锁
        }

        //run函数结束，isRunning()获得的返回值为false，可以再次开启线程
    }
signals:
    void resultReady(int value);

private:
    //标志位，是否需要被停止
    bool m_bNeedStopped;
    QMutex m_mutex;
    int m_progressValue;
};

#endif // WORKERTHREAD_H
